package com.shenxuchen.crm.web.listener;

import com.shenxuchen.crm.pojo.Value;
import com.shenxuchen.crm.service.ValueService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.ContextLoader;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebListener
public class LoadCacheListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        // 获取Spring容器
        BeanFactory beanFactory = ContextLoader.getCurrentWebApplicationContext();
        ValueService valueService = beanFactory.getBean(ValueService.class);

        List<Value> values = valueService.getAll();

        /*
            将数据进一步处理之后再缓存！
            key: 字典类型， List: 字典类型对应的字典值 Map: 2个key：value、text
         */
        Map<String, List<Map>> optionsMap = new HashMap<>();

        for (Value value : values) {
            List<Map> optionsList = optionsMap.get(value.getTypeCode());
            if (optionsList == null) {
                optionsList = new ArrayList<>();
                optionsMap.put(value.getTypeCode(), optionsList);
            }
            optionsList.add(new HashMap(){{
                put("value", value.getValue());
                put("text", value.getText());
            }});
        }

        for (Map.Entry<String, List<Map>> stringListEntry : optionsMap.entrySet()) {
            System.out.println(stringListEntry.getKey() + ":" + stringListEntry.getValue());
        }

        // 将处理好的数据添加到ServletContext(application)作用域
        sce.getServletContext().setAttribute("optionsCache", optionsMap);
    }
}
